package tcp.文件上传;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

//接收方法。服务端
public class test1 {
    public static void main(String[] args) {
        ServerSocket serverSocket = null;
        Socket accept = null;
        InputStream inputStream =null;
        FileOutputStream fos = null;
        OutputStream outputStream=null;
        try {
            //1.给服务器地址端口号
            serverSocket = new ServerSocket(8080);
            //2.接收消息
            //2.1阻塞监听
            accept = serverSocket.accept();


            //3.获取输入，获取文件
            inputStream = accept.getInputStream();//返回此套接字的输入流。

            //4.输出文件,使用管道方法
            fos = new FileOutputStream(new File("2019-08-12 135112.jpg"));
            byte[] wj = new byte[1024];
            int len;
            while ((len = inputStream.read(wj))!= -1) {
                fos.write(wj,0,len);
            }

            System.out.println(fos.toString());

            //5.告诉客户端接收完成
//            accept.shutdownInput();
            outputStream = accept.getOutputStream();
            outputStream.write("我接收完了".getBytes());



            } catch(IOException e){
                e.printStackTrace();
            }finally{
            try {
                if (outputStream != null){
                    outputStream.close();
                }
                if (fos != null){
                    fos.close();
                }
                if (inputStream !=null){
                    inputStream.close();
                }
                if (accept != null){
                    accept.close();
                }
                if (serverSocket != null){
                    serverSocket.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        }
    }
